<?php
/**
 * @abstract 扫码支付后统一下单
 */

namespace services\models;

use Opwechat\Phppayment\Lib\WxPayNotify;
use Opwechat\Phppayment\Lib\WxPayUnifiedOrder;
use Opwechat\Phppayment\Lib\WxPayApi;

class NativeNotifyCallBack extends  WxPayNotify
{
    public function unifiedorder($openId, $product_id)
    {
        //orderInfo 的order_id怎么获取
    
        // 获取订单信息
        $order_info = Payment::getOrderInfoByPramas(['order_info_id'=>$product_id]);
    
        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("有试吗");
        //$input->SetAttach("test");
        $input->SetOut_trade_no($order_info->order_sn);
        $input->SetTotal_fee($order_info->order_amount * 100);
        //$input->SetTime_start(date("YmdHis"));
        //$input->SetTime_expire(date("YmdHis", time() + 600));
        //$input->SetGoods_tag("test");
        $input->SetNotify_url(\Yii::$app->params['wxpay']['notify_url']);
        $input->SetTrade_type("NATIVE");
        $input->SetOpenid($openId);
        $input->SetProduct_id($product_id);
        $result = WxPayApi::unifiedOrder($input);
    
        return $result;
        
    }
    
    public function NotifyProcess($data, &$msg)
    {
        //echo "处理回调";
        if(!array_key_exists("openid", $data) ||
            !array_key_exists("product_id", $data))
        {
            $msg = "回调数据异常";
            return false;
        }
    
        $openid = $data["openid"];
        $product_id = $data["product_id"];
    
        //统一下单
        $result = $this->unifiedorder($openid, $product_id);
        if(!array_key_exists("appid", $result) ||
            !array_key_exists("mch_id", $result) ||
            !array_key_exists("prepay_id", $result))
        {
            $msg = "统一下单失败";
            return false;
        }
    
        $this->SetData("appid", $result["appid"]);
        $this->SetData("mch_id", $result["mch_id"]);
        $this->SetData("nonce_str", WxPayApi::getNonceStr());
        $this->SetData("prepay_id", $result["prepay_id"]);
        $this->SetData("result_code", "SUCCESS");
        $this->SetData("err_code_des", "OK");
        
        return true;
    }  
}
?>